//
//  KLSendKeyTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/17.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//


#import "KLSendKeyTableViewController.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "JRToast.h"
#import "HemaConst.h"
#import "Masonry.h"
#import "HemaFunction.h"
#import <objc/runtime.h>
#import "BuleFuction.h"
#import "SSKeychain.h"
#import "NSData+hex.h"
#import "NSString+Hex.h"

static NSString *AssociatedKeyAlertView = @"AlertViewIndexPath";
static BOOL isEditingMode = NO;

@interface KLSendKeyTableViewController ()<UIAlertViewDelegate>
{
    NSMutableArray *selectedArr;//二级列表是否展开状态
    NSMutableArray *preparingDeleteKeyArr;//即将被删除的数组
    UIButton *rightBtn;//右上角的编辑按钮
    NSDictionary *publicKeysDic;//所有公钥集
}
@property (nonatomic,strong) NSMutableArray *key_list_arr;//所有钥匙的数组

@property (nonatomic,strong) NSMutableArray *keysNamesArr;//可打开锁的名字数组
@property (nonatomic,strong) NSMutableArray *keysOrderOKArr;//排序完成后的数组

@end

@implementation KLSendKeyTableViewController
-(void)viewWillAppear:(BOOL)animated{
    [self refreshKeyList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化导航栏
    [self naveSet];
    self.tableView.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    selectedArr = [[NSMutableArray alloc] init];
    
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.keysNamesArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:string]) {
        UIImageView *imageV = (UIImageView *)[self.tableView viewWithTag:20000+section];
        imageV.image = [UIImage imageNamed:@"buddy_header_arrow_down@2x.png"];
        NSMutableArray *arr = self.keysOrderOKArr[section];
        return arr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sendKeyList"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"sendKeyList"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
   
    //当前是第几个表头
    NSString *indexStr = [NSString stringWithFormat:@"%ld",(long)indexPath.section];
    if (![selectedArr containsObject:indexStr]) {
        return cell;
    }
    
    NSDictionary *lockDic = self.keysOrderOKArr[indexPath.section][indexPath.row];
    
    NSString *valid_type = [lockDic objectForKey:@"valid_type"];
    if(valid_type.integerValue == 1){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"未生效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(238, 230, 133);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if(valid_type.integerValue == 2){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"已过期";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(240, 101, 101);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 4){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"可使用";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 3){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"永久有效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }
    
    UIImageView *iv = [[UIImageView alloc]init];
    iv.image = [UIImage imageNamed:@"key_msg"];
    [cell.contentView addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell);
        make.size.mas_equalTo(CGSizeMake(34, 34));
        make.left.equalTo(cell.contentView).with.offset(5);
    }];
    
    UILabel *lockMasterName = [[UILabel alloc]init];
    if([[lockDic objectForKey:@"type"] isEqualToString:@"0"]){
        lockMasterName.text = @"锁主钥匙";
    }
//    else if([[lockDic objectForKey:@"type"] isEqualToString:@"1"]){
//        lockMasterName.text = @"平等钥匙";
//        iv.hidden = YES;
//    }else if([[lockDic objectForKey:@"type"] isEqualToString:@"2"]){
//        lockMasterName.text = @"临时钥匙";
//        iv.hidden = YES;
//    }
    [cell.contentView addSubview:lockMasterName];
    [lockMasterName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).with.offset(5);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell.contentView).with.offset(45);
    }];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    if([[lockDic objectForKey:@"type"] isEqualToString:@"0"]){
        nameLabel.text = [lockDic objectForKey:@"name"];
        nameLabel.textAlignment = NSTextAlignmentRight;
        nameLabel.textColor = [UIColor lightGrayColor];
        nameLabel.alpha = 0.8;
        nameLabel.font = [UIFont systemFontOfSize:15];
        nameLabel.numberOfLines = 1;
        nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
        [cell.contentView addSubview:nameLabel];
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(lockMasterName).with.offset(0);
            make.right.equalTo(cell.contentView).with.offset(-40);
            make.left.equalTo(lockMasterName).with.offset(80);
        }];
    }
    
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.textColor = [UIColor lightGrayColor];
    timeLabel.alpha = 0.8;
    timeLabel.font = [UIFont systemFontOfSize:13];
    NSString *starTime = [lockDic objectForKey:@"startdate"];
    starTime = [starTime substringToIndex:16];
    NSString *endTime = [lockDic objectForKey:@"enddate"];
    endTime = [endTime substringToIndex:16];
    if([[lockDic objectForKey:@"parentflag"] isEqualToString:@"1"]){
        timeLabel.text = @"永久有效";
    }else{
        timeLabel.text = [NSString stringWithFormat:@"有效期:%@至%@",starTime,endTime];
    }
    [cell.contentView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).with.offset(30);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell.contentView).with.offset(45);
    }];
    
    if(![[lockDic objectForKey:@"parentflag"] isEqualToString:@"1"]) {
        UILabel *phoneLabel = [[UILabel alloc]init];
        phoneLabel.textColor = [UIColor lightGrayColor];
        phoneLabel.alpha = 0.8;
        phoneLabel.font = [UIFont systemFontOfSize:13];
        if([[lockDic objectForKey:@"parentflag"] isEqualToString:@"3"]){//发出的钥匙
            phoneLabel.text = [NSString stringWithFormat:@"此钥匙下发至用户:%@ （%@）",[lockDic objectForKey:@"recevier_phone"],[lockDic objectForKey:@"recevier_username"]];
        }
        [cell.contentView addSubview:phoneLabel];
        [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).with.offset(50);
            make.height.mas_equalTo(25);
            make.left.equalTo(cell.contentView).with.offset(45);
        }];
    }
    
    UILabel *address = [[UILabel alloc]init];
    address.textColor = [UIColor lightGrayColor];
    address.numberOfLines = 1;
    address.lineBreakMode = NSLineBreakByTruncatingMiddle;
    address.alpha = 0.8;
    address.font = [UIFont systemFontOfSize:13];
    address.text = [NSString stringWithFormat:@"地址:%@",[lockDic objectForKey:@"address"]];
    [cell.contentView addSubview:address];
    if([[lockDic objectForKey:@"type"] isEqualToString:@"0"]){
        [address mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).with.offset(50);
            make.height.mas_equalTo(25);
            make.left.equalTo(cell.contentView).with.offset(45);
            make.right.equalTo(cell.contentView).with.offset(-15);
        }];
    }else{
        [address mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).with.offset(70);
            make.height.mas_equalTo(25);
            make.left.equalTo(cell.contentView).with.offset(45);
            make.right.equalTo(cell.contentView).with.offset(-15);
        }];
    }
    
    NSArray *sectionKeys = self.keysOrderOKArr[indexPath.section];
    if (indexPath.row != sectionKeys.count-1) {
        if([[lockDic objectForKey:@"type"] isEqualToString:@"0"]){
            UIImageView *imageLine = [[UIImageView alloc]initWithFrame:CGRectMake(40, 74, UI_View_Width-45, 1.5)];
            imageLine.image = [UIImage imageNamed:@"line.png"];
            [cell.contentView addSubview:imageLine];
        }else{
            UIImageView *imageLine = [[UIImageView alloc]initWithFrame:CGRectMake(40, 94, UI_View_Width-45, 1.5)];
            imageLine.image = [UIImage imageNamed:@"line.png"];
            [cell.contentView addSubview:imageLine];
        }
    }
    
    return cell;
}

//-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"反选cell");
//}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"选中cell");
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *lockDic = self.keysOrderOKArr[indexPath.section][indexPath.row];
    if([[lockDic objectForKey:@"parentflag"] isEqualToString:@"1"]){
        return 75;
    }else{
        return 95;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40.0f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vw = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 40)];
    vw.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, UI_View_Width, 40)];
    NSDictionary *lockMaster = self.keysOrderOKArr[section][0];
    label.text = [NSString stringWithFormat:@"%@ (%@)",self.keysNamesArr[section],[lockMaster objectForKey:@"name"]];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = RGB_UI_COLOR(132, 112, 255);
    label.font = [UIFont systemFontOfSize:15];
    label.alpha = 0.75;
    [vw addSubview:label];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 20, 20)];
    imageView.tag = 20000+section;
    
    //判断是不是选中状态
    NSString *string = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:string]) {
        imageView.image = [UIImage imageNamed:@"buddy_header_arrow_down@2x.png"];
    }
    else{
        imageView.image = [UIImage imageNamed:@"buddy_header_arrow_right@2x.png"];
    }
    [vw addSubview:imageView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, UI_View_Width, 40);
    button.tag = 100+section;
    [button addTarget:self action:@selector(doButton_s:) forControlEvents:UIControlEventTouchUpInside];
    [vw addSubview:button];
    
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 39, UI_View_Width, 1.5)];
    lineImage.image = [UIImage imageNamed:@"line.png"];
    [vw addSubview:lineImage];
    
    return vw;
}-(void)doButton_s:(UIButton *)sender{
    NSString *string = [NSString stringWithFormat:@"%zd",sender.tag-100];
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if([selectedArr containsObject:string]){
        [selectedArr removeObject:string];
    }else{
        [selectedArr addObject:string];
    }
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:sender.tag-100];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0)
        return NO;
    else
        return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"删除钥匙" message:@"删除后对方将不再能开锁" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
        objc_setAssociatedObject(alert, &AssociatedKeyAlertView, indexPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
        [alert show];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

//初始化导航栏
-(void)naveSet{
    self.navigationController.navigationBarHidden = NO;
    self.title = @"发出的钥匙";
    self.tableView.tableFooterView = [[UIView alloc]init];
//    rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 33, 30)];
//    rightBtn.layer.masksToBounds = YES;
//    rightBtn.layer.borderColor = RGB_UI_COLOR(109,158,235).CGColor;
//    rightBtn.layer.cornerRadius = 5;
//    rightBtn.layer.borderWidth = 0;
//    [rightBtn addTarget:self action:@selector(bulkEdit:) forControlEvents:UIControlEventTouchUpInside];
//    [rightBtn setImage:[UIImage imageNamed:@"编辑钥匙"] forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}-(void)bulkEdit:(UIBarButtonItem *)sender{
    preparingDeleteKeyArr = [NSMutableArray array];
    if(isEditingMode == NO){
        rightBtn.frame = CGRectMake(0, 0, 45, 30);
        rightBtn.layer.borderWidth = 1;
        [rightBtn setImage:nil forState:UIControlStateNormal];
        [rightBtn setTitle:@"删除" forState:UIControlStateNormal];
        [rightBtn setTitleColor:RGB_UI_COLOR(255, 102, 102) forState:UIControlStateNormal];
    }else{
        rightBtn.frame = CGRectMake(0, 0, 33, 30);
        rightBtn.layer.borderWidth = 0;
        [rightBtn setImage:[UIImage imageNamed:@"编辑钥匙"] forState:UIControlStateNormal];
        [rightBtn setTitle:nil forState:UIControlStateNormal];
    }
    NSLog(@"点击了右上角图标");
    isEditingMode = !isEditingMode;
    [self.tableView setEditing:isEditingMode animated:YES];
}

#pragma mark - 刷新钥匙列表
-(void)refreshKeyList{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    [KLHttpAPI requestKeyListWith:token completionHandler:^(NSDictionary *responseDic) {
        NSString *isSuccess = [responseDic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSDictionary *infor = [responseDic objectForKey:@"infor"];
            NSArray *listItems = [infor objectForKey:@"listItems"];
            if(![[infor objectForKey:@"totalCount"] isEqualToString:@"0"] && ![[infor objectForKey:@"listItems"] isKindOfClass:[NSNull class]]){
                self.key_list_arr = [NSMutableArray arrayWithArray:listItems];
                //拿到钥匙列表后存入底层
                NSMutableArray *masterKeysArr = [NSMutableArray array];
                NSMutableArray *childKeysArr = [NSMutableArray array];
                //目前存的只有锁主钥匙,之后要做判断，并分开存储锁主钥匙和子钥匙
                for (NSDictionary *keyDic in self.key_list_arr) {
                    NSString *valid_type = [keyDic objectForKey:@"valid_type"];
                    if(valid_type.integerValue == 1 || valid_type.integerValue == 2){
                        continue;
                    }
                    
                    NSString *type = [keyDic objectForKey:@"keyright"];
                    if(type.integerValue == 3){//0是不可转发钥匙，1是可转发钥匙，2是二级锁主钥匙，3是锁主钥匙
                        [masterKeysArr addObject:keyDic];
                    }else{
                        NSString *parentFlag = [keyDic objectForKey:@"parentflag"];//2是发出的钥匙，3是收到的钥匙
                        if(parentFlag.integerValue == 2){
                            [childKeysArr addObject:keyDic];
                        }
                    }
                }
                [[NSUserDefaults standardUserDefaults] setObject:masterKeysArr forKey:MASTER_KEY_ARRAY];
                [[NSUserDefaults standardUserDefaults] setObject:childKeysArr forKey:SUBMIT_KEY_ARRAY];
            }else{
                [KLHelp setNoDateImageWithView:self.view type:0];
            }
        }else{
            [JRToast showWithText:[responseDic objectForKey:@"msg"]];
        }
        //隐藏进度条
        [KLHelp hideAllHUDsForView:self.tableView animated:YES];
        //对钥匙进行分组
        [self groupingKeys];
        
        // 打印数组
        NSString *key_list_arrjson = [KLHelp jsonFromArray:self.key_list_arr];
        NSString *keysNamesArrJson = [KLHelp jsonFromArray:self.keysNamesArr];
        NSString *keysOrderOKArrJson = [KLHelp jsonFromArray:self.keysOrderOKArr];
        NSLog(@"%@",key_list_arrjson);
        NSLog(@"%@",keysNamesArrJson);
        NSLog(@"%@",keysOrderOKArrJson);
        
        [self.tableView reloadData];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp setNoDateImageWithView:self.view type:1];
    }];
    
   
}

//对钥匙进行分组
-(void)groupingKeys{
    self.keysNamesArr = [NSMutableArray array];
    NSMutableArray *sendKeys = [[NSMutableArray alloc]init]; // 保存的是字典
    //取出所有发出的钥匙
   
    for (NSDictionary *keyDic in self.key_list_arr) {
        if(![[keyDic objectForKey:@"parentflag"] isEqualToString:@"2"]){
            [sendKeys addObject:keyDic];
        }
    }
    
    NSString *jsonStr =  [KLHelp jsonFromArray:sendKeys];
    NSLog(@"%@",jsonStr);
    
    //获得所有不同的锁编码
    for (NSDictionary *keyDic in sendKeys) {
        NSString *uname = [keyDic objectForKey:@"uname"];
        for (NSString *lockUname in self.keysNamesArr) {
            if([lockUname isEqualToString:uname]){
                [self.keysNamesArr removeObject:lockUname];
                break;
            }
        }
        
        [self.keysNamesArr addObject:uname];
    }
    
    if(self.keysNamesArr.count == 0){
        [KLHelp setNoDateImageWithView:self.view type:0];
    }
    //对收到的钥匙分类
    NSMutableArray *allGroupArr = [NSMutableArray array];
    for (int i = 0; i < self.keysNamesArr.count; i++) {
        NSMutableArray *sigleGroupArr = [NSMutableArray array];
        for (NSDictionary *keyDic in sendKeys) {
            if([[keyDic objectForKey:@"uname"] isEqualToString:self.keysNamesArr[i]]){
                [sigleGroupArr addObject:keyDic];
            }
        }
        [allGroupArr addObject:sigleGroupArr];
    }
    NSLog(@"allGroupArr:%@",allGroupArr);
    NSString *jsonArrStr = [KLHelp jsonFromArray:allGroupArr];
    NSLog(@"%@",jsonArrStr);

    self.keysOrderOKArr = [allGroupArr copy]; // 数组 里面放数组
    
}

#pragma mark - UIAlertViewDelegate的代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //获取删除
    NSIndexPath *indexPath = (NSIndexPath *)objc_getAssociatedObject(alertView, &AssociatedKeyAlertView);
    NSMutableArray *lockSection = [NSMutableArray arrayWithArray:self.keysOrderOKArr[indexPath.section]];
    [lockSection removeObjectAtIndex:indexPath.row];
    [lockSection removeObjectAtIndex:0];
    if(buttonIndex == 1){
        NSDictionary *keyDic = self.keysOrderOKArr[indexPath.section][indexPath.row];
        [KLHttpAPI removeOutOfDateChildKeyWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] key_id:[keyDic objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
            NSDictionary *backDic = [operation responseJSON];
            NSString *issuccess = [backDic objectForKey:@"success"];
            if(issuccess.integerValue == 1){
                NSString *commondCode = [backDic objectForKey:@"infor"];
                NSLog(@"***********%@***********",commondCode);
                //创建一个数组装入所有的子钥匙和其对应的id
                NSMutableArray *newKeys = [NSMutableArray array];
                //循环更新子钥匙
                for (NSDictionary *keyDic in lockSection) {
                    NSString *everyNewKey = [self updataChildKeyWithKeyDictionary:keyDic commondCode:commondCode];
                    [newKeys addObject:everyNewKey];
                }
                //更新新钥匙组
                [self updataNewKeysWithKeysArr:newKeys];
            }else{
                [JRToast showWithText:[backDic objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
        }];
    }
}

#pragma mark - 重新打包子钥匙
-(NSString *)updataChildKeyWithKeyDictionary:(NSDictionary *)keyDic commondCode:(NSString *)commondCode{
    NSString *keyId = [keyDic objectForKey:@"id"];
    NSString *startDate = [keyDic objectForKey:@"startdate"];
    NSString *endDate = [keyDic objectForKey:@"enddate"];
    NSString *lockUname = [keyDic objectForKey:@"uname"];
    NSString *userPhone = [keyDic objectForKey:@"recevier_phone"];
    //获取公钥
    NSString *publicKey = [publicKeysDic objectForKey:lockUname];
    //给锁的时间
    NSString *starDateToLock = [startDate substringFromIndex:2];
    starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@" " withString:@""];
    starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@"-" withString:@""];
    starDateToLock = [starDateToLock stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *endDateToLock = [endDate substringFromIndex:2];
    endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@" " withString:@""];
    endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@"-" withString:@""];
    endDateToLock = [endDateToLock stringByReplacingOccurrencesOfString:@":" withString:@""];
    //打包子钥匙
//    NSData *childKeyData = [BuleFuction packChildkeyToData:publicKey mobileStr:userPhone startTime:starDateToLock endTime:endDateToLock commondCode:commondCode];
//    NSString *childKeyStr = [childKeyData convertDataToHexStr:childKeyData];
//    NSString *keyWithId = [NSString stringWithFormat:@"%@#%@",childKeyStr,keyId];
    
    return @"";
}

//上传新子钥匙组
-(void)updataNewKeysWithKeysArr:(NSArray *)newKeys{
    [KLHttpAPI requestUpdataAllTemporaryKeysWithPackageArr:newKeys completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"更新所有钥匙的返回数据:%@",operation.responseJSON);
        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            //要先更新钥匙再做刷新
            [self refreshKeyList];
        }
    } errorHandler:^(NSString *error) {
        
    }];
}
@end
